/*
 * PersonTimePanel.java
 *
 * Created on 21 July 2004, 11:00
 * Copyright (C) 2004, Velocityme Partnership
 */

package com.velocityme.client.gui.time;

import com.velocityme.client.gui.calendar.CalendarDatePanel;
import com.velocityme.client.gui.calendar.CalendarListener;
import com.velocityme.client.gui.exception.ExceptionWindow;
import com.velocityme.client.utility.StatelessRemoteClientSessionUtil;
import com.velocityme.entity.PermissionBean;
import com.velocityme.interfaces.KeySession;
import com.velocityme.interfaces.NodePK;
import com.velocityme.interfaces.PermissionPK;
import com.velocityme.interfaces.PersonPK;
import com.velocityme.interfaces.TaskPK;
import com.velocityme.utility.DurationFormat;
import com.velocityme.utility.InvalidKeyException;
import com.velocityme.utility.PermissionDeniedException;
import com.velocityme.valueobjects.TimeValue;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import javax.ejb.CreateException;
import javax.naming.NamingException;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;

/**
 *
 * @author  Robert
 */
public class PersonTimePanel extends javax.swing.JPanel implements CalendarListener {
    
    private KeySession m_key;
    private PersonPK m_personPK;
    private PersonTimeTableModel m_modelTime;
    private CalendarDatePanel m_datePanel;
    private Date m_date = null;

    /** Creates new form PersonTimePanel */
    public PersonTimePanel(KeySession p_key, PersonPK p_personPK) {
        initComponents();
        m_key = p_key;
        m_personPK = p_personPK;
        m_datePanel = new CalendarDatePanel();
        m_datePanel.registerListener(this);
        java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        gridBagConstraints.weightx = 1.0;
        jPanel1.add(m_datePanel, gridBagConstraints);
        jTableEntries.getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    }
    
    public void setSelectAction(String dt) {
        try {
            Date start = m_datePanel.getDate();
            Date stop = m_datePanel.getDate();
            long time = stop.getTime();
            stop.setTime(time + 999 + 59*1000 + 59*60*1000 + 23*60*60*1000); // Make time 23h59:59.999
            Collection timeValues = StatelessRemoteClientSessionUtil.getSession().getPersonTimeValues(m_key, m_personPK, start, stop);
            m_modelTime.setTimeValues(timeValues);
            jButtonEdit.setEnabled(false);
            jButtonDelete.setEnabled(false);
            // determine total duration
            Iterator i = timeValues.iterator();
            long totalDuration = 0;
            while(i.hasNext()) {
                TimeValue value = (TimeValue)i.next();
                totalDuration += value.getStopTime().getTime() - value.getStartTime().getTime();
            }
            jLabelDuration.setText(DurationFormat.formatDuration(totalDuration));
        }
        catch(Exception e) {
            ExceptionWindow.showError(e);
        }
    }    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel2 = new javax.swing.JPanel();
        jButtonEdit = new javax.swing.JButton();
        jButtonDelete = new javax.swing.JButton();
        jScrollPaneEntries = new javax.swing.JScrollPane();
        m_modelTime = new PersonTimeTableModel();
        jTableEntries = new javax.swing.JTable(m_modelTime);
        jPanel1 = new javax.swing.JPanel();
        jLabelDate = new javax.swing.JLabel();
        jLabelDurationHeading = new javax.swing.JLabel();
        jLabelDuration = new javax.swing.JLabel();

        setLayout(new java.awt.BorderLayout());

        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jPanel2.setLayout(new java.awt.GridLayout(1, 0));

        jButtonEdit.setText("Edit");
        jButtonEdit.setEnabled(false);
        jButtonEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEditActionPerformed(evt);
            }
        });

        jPanel2.add(jButtonEdit);

        jButtonDelete.setText("Delete");
        jButtonDelete.setEnabled(false);
        jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteActionPerformed(evt);
            }
        });

        jPanel2.add(jButtonDelete);

        add(jPanel2, java.awt.BorderLayout.SOUTH);

        jScrollPaneEntries.setPreferredSize(new java.awt.Dimension(3, 160));
        jTableEntries.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableEntriesMouseClicked(evt);
            }
        });

        jScrollPaneEntries.setViewportView(jTableEntries);

        add(jScrollPaneEntries, java.awt.BorderLayout.CENTER);

        jPanel1.setLayout(new java.awt.GridBagLayout());

        jPanel1.setMinimumSize(new java.awt.Dimension(0, 0));
        jLabelDate.setText("Date:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        jPanel1.add(jLabelDate, gridBagConstraints);

        jLabelDurationHeading.setText("Duration:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        jPanel1.add(jLabelDurationHeading, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        jPanel1.add(jLabelDuration, gridBagConstraints);

        add(jPanel1, java.awt.BorderLayout.NORTH);

    }//GEN-END:initComponents

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        if (m_date == null)
            m_date = new Date();
        m_datePanel.setDate(m_date);        
    }//GEN-LAST:event_formComponentShown

    private void jTableEntriesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableEntriesMouseClicked
        // TODO add your handling code here:
        try {
            int row = jTableEntries.getSelectedRow();
            if (row >= 0) {
                TaskPK taskPK = m_modelTime.getValue(row).getTaskValue().getPrimaryKey();
                Set setPermissions = StatelessRemoteClientSessionUtil.getSession().getAssignedPermissions(m_key, new NodePK(taskPK.getTaskId()));
                jButtonEdit.setEnabled(setPermissions.contains(new PermissionPK(new Integer(PermissionBean.TIME_EDIT))));
                jButtonDelete.setEnabled(setPermissions.contains(new PermissionPK(new Integer(PermissionBean.TIME_DELETE))));
            }
            else {
                jButtonEdit.setEnabled(false);
                jButtonDelete.setEnabled(false);
            }
        }
        catch(Exception e) {
            ExceptionWindow.showError(e);
        }        
    }//GEN-LAST:event_jTableEntriesMouseClicked

    private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteActionPerformed
        // TODO add your handling code here:
        try {
            int row = jTableEntries.getSelectedRow();
            if (JOptionPane.showConfirmDialog(null, "Are you sure you wish to delete the time entry?", "Delete", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                StatelessRemoteClientSessionUtil.getSession().taskTimeDelete(m_key, m_modelTime.getValue(row).getPrimaryKey());
                m_modelTime.removeRows(row, row);
                jButtonEdit.setEnabled(false);
                jButtonDelete.setEnabled(false);
            }
        }
        catch(RemoteException e) {
            ExceptionWindow.showError(e);
        }
        catch(CreateException e) {
            ExceptionWindow.showError(e);
        }
        catch(NamingException e) {
            ExceptionWindow.showError(e);
        }
        catch(PermissionDeniedException e) {
            ExceptionWindow.showError(e);
        }
        catch(InvalidKeyException e) {
            ExceptionWindow.showError(e);
        }        
    }//GEN-LAST:event_jButtonDeleteActionPerformed

    private void jButtonEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEditActionPerformed
        // TODO add your handling code here:
        JTabbedPane tabbedPane = (JTabbedPane)getParent();
        int row = jTableEntries.getSelectedRow();
        TaskPK taskPK = m_modelTime.getValue(row).getTaskValue().getPrimaryKey();
        TimeControl timeControl = new TimeControl(m_key, taskPK, m_modelTime.getValue(row).getPrimaryKey());
        tabbedPane.addTab("Edit Time", timeControl);
        tabbedPane.setSelectedComponent(timeControl);        
    }//GEN-LAST:event_jButtonEditActionPerformed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonDelete;
    private javax.swing.JButton jButtonEdit;
    private javax.swing.JLabel jLabelDate;
    private javax.swing.JLabel jLabelDuration;
    private javax.swing.JLabel jLabelDurationHeading;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPaneEntries;
    private javax.swing.JTable jTableEntries;
    // End of variables declaration//GEN-END:variables
    
}
